using System.ServiceModel;

namespace CustomWcfContext
{





	/// <summary>
	/// Your WCF context state implemeintation.
	/// <para/><para/>
	/// it3xl.ru:<para/>
	/// The grain is here.<para/>
	/// Only in this class is all you need to copy and get started at your project.
	/// </summary>
	public class WcfContext<TState> : IExtension<OperationContext>
	{
		/// <summary>
		/// Your current state.
		/// </summary>
		public static TState Current
		{
			get
			{
				var contextState = OperationContext.Current.Extensions.Find<WcfContext<TState>>();

				if (contextState == null)
				{
					return default(TState);
				}

				return contextState.State;
			}
		}

		/// <summary>
		/// Your state.
		/// </summary>
		private TState State { get; set; }


		/// <summary>
		/// Construcrtor.
		/// </summary>
		/// <param name="state">Your state to store.</param>
		public WcfContext(TState state)
		{
			State = state;
		}

		/// <summary>
		/// Setting of your state to the WCF context.
		/// </summary>
		/// <param name="state"></param>
		public static void SetCurrent(TState state)
		{
			if (OperationContext.Current == null)
			{
				// Have no WCF context at that point.
				return;
			}

			// it3xl.ru: Be aware! Null is also the state! Don't ignore it to add at context!

			// The main job is here.
			OperationContext.Current.Extensions.Add(new WcfContext<TState>(state));
		}

		#region Implementation of IExtension<OperationContext>

		public void Attach(OperationContext owner)
		{
			// it3xl.ru: Not used.
		}

		public void Detach(OperationContext owner)
		{
			// it3xl.ru: Not used.
		}

		#endregion

	}




















}